package com.yami.shop.multishop.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.dto.CopyrightWorksDto;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.enums.ProdType;
import com.yami.shop.bean.event.EsProductUpdateEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.CopyrightWorksParam;
import com.yami.shop.bean.param.ProdLangParam;
import com.yami.shop.bean.param.ProductParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.BeanUtil;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.nft.common.dto.NftDenomDto;
import com.yami.shop.nft.common.model.NftApply;
import com.yami.shop.nft.common.model.NftApplyImg;
import com.yami.shop.nft.common.model.NftDenom;
import com.yami.shop.nft.common.service.NftApplyService;
import com.yami.shop.nft.common.service.NftDenomService;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.CopyrightWorksService;
import com.yami.shop.service.ProdParameterService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.UserCopyrightService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.log4j.Log4j2;
import org.jetbrains.annotations.NotNull;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * @ClassName:
 * @Description: 版权登记
 * @Author:
 * @Date: 2
 * @History 修改描述
 */
@RestController
@RequestMapping(value = "/shop/copyright")
@Log4j2
public class CopyrightController {
    @Autowired
    private CopyrightWorksService copyrightWorksService;

    @Autowired
    private NftDenomService nftDenomService;

    @Autowired
    private NftApplyService nftApplyService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ProdParameterService prodParameterService;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private UserCopyrightService userCopyrightService;


    @GetMapping("/page")
    @Operation(summary = "分页获取产权登记作品申请列表", description = "分页获取产权登记作品申请列表")
    public ServerResponseEntity<IPage<CopyrightWorks>> page(@ParameterObject CopyrightWorksParam copyrightWorksParam, PageParam<CopyrightWorks> page) {
        IPage<CopyrightWorks> copyrightWorksIPage = copyrightWorksService.page(page, new LambdaQueryWrapper<CopyrightWorks>()
                .like(StrUtil.isNotBlank(copyrightWorksParam.getWorksName()), CopyrightWorks::getWorksName, copyrightWorksParam.getWorksName())
                .like(StrUtil.isNotBlank(copyrightWorksParam.getWorksType()), CopyrightWorks::getWorksType, copyrightWorksParam.getWorksType())
                .eq(StrUtil.isNotBlank(copyrightWorksParam.getUserId()), CopyrightWorks::getUserId, copyrightWorksParam.getUserId())
                .eq(StrUtil.isNotBlank(copyrightWorksParam.getDenomId()), CopyrightWorks::getDenomId, copyrightWorksParam.getDenomId())
                .eq(ObjectUtil.isNotNull(copyrightWorksParam.getProdId()), CopyrightWorks::getProdId, copyrightWorksParam.getProdId())
                .eq(CopyrightWorks::getShopId, SecurityUtils.getShopUser().getShopId())
                .eq(StrUtil.isNotBlank(copyrightWorksParam.getStatus()), CopyrightWorks::getStatus, copyrightWorksParam.getStatus())
                .orderByDesc(CopyrightWorks::getCreateTime));
        return ServerResponseEntity.success(copyrightWorksIPage);
    }

    @GetMapping("/info/{worksId}")
    @Operation(summary = "获取产权登记作品申请信息", description = "获取产权登记作品申请信息")
    public ServerResponseEntity<CopyrightWorksDto> info(@PathVariable("worksId") Long worksId) {
        CopyrightWorks copyrightWorks = copyrightWorksService.getById(worksId);
        CopyrightWorksDto shopDetailDto = BeanUtil.map(copyrightWorks, CopyrightWorksDto.class);
        UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, copyrightWorks.getUserId()));
        shopDetailDto.setUserCopyright(userCopyright);
        return ServerResponseEntity.success(shopDetailDto);
    }

    @PostMapping("/audit")
    @Operation(summary = "审核产权登记作品申请")
    public ServerResponseEntity<Boolean> audit(@RequestBody CopyrightWorksParam copyrightWorksParam) {
        CopyrightWorks copyrightWorks = copyrightWorksService.getById(copyrightWorksParam.getWorksId());
        if (ObjectUtil.isNull(copyrightWorks)) {
            throw new YamiShopBindException("记录不存在！");
        }
        if (ObjectUtil.isNotNull(copyrightWorks) && (copyrightWorks.getStatus().equals("2") || copyrightWorks.getStatus().equals("5"))) {
            throw new YamiShopBindException("记录状态异常！");
        }
        // 审核通过
        if (copyrightWorksParam.getStatus().equals("2")) {
            // 新建铸币步骤
            NftDenomDto nftDenomDto = new NftDenomDto();
            nftDenomDto.setShopId(SecurityUtils.getShopUser().getShopId());
            nftDenomDto.setDenomName(copyrightWorks.getWorksName());
            nftDenomDto.setBlockchainCode("dt");
            nftDenomDto.setSysType(1);
            NftDenom nftDenom;
            // 新建品类
            nftDenom = nftDenomService.insertDenom(nftDenomDto);
            NftApply nftApply = nftApply(nftDenom, copyrightWorks);
            // 铸币申请提交
            if (!nftApplyService.copyrightApplyNft(nftApply, nftDenom)) {
                throw new RuntimeException("铸币申请异常！");
            }
            UserCopyright userCopyright = userCopyrightService.getOne(new LambdaQueryWrapper<UserCopyright>().eq(UserCopyright::getUserId, copyrightWorks.getUserId()));
            // 新建商品步骤
            ProductParam productParam = buildProductParam(copyrightWorks, nftDenom, nftApply, userCopyright);
            productService.saveProduct(productParam);
            // 商品新建成功 修改 商品品类绑定状态
            nftDenomService.updateDenomStatusByDenomId(nftDenom.getDenomId());
            try {
                eventPublisher.publishEvent(new EsProductUpdateEvent(productParam.getProdId(), null, EsOperationType.SAVE));
                // 移除缓存
                prodParameterService.removeCacheByProdId(productParam.getProdId());
            } catch (Exception e) {
                log.error("商品新增数据异常了", e);
            }
            // 更新产权登记作品申请状态
            copyrightWorksService.update(new LambdaUpdateWrapper<CopyrightWorks>()
                    .set(CopyrightWorks::getStatus, copyrightWorksParam.getStatus())
                    .set(StrUtil.isNotBlank(copyrightWorksParam.getReason()), CopyrightWorks::getReason, copyrightWorksParam.getReason())
                    .set(StrUtil.isNotBlank(copyrightWorksParam.getReasonStatus()), CopyrightWorks::getReasonStatus, copyrightWorksParam.getReasonStatus())
                    // .set(CopyrightWorks::getShopId, SecurityUtils.getShopUser().getShopId())
                    .set(CopyrightWorks::getDenomId, nftDenom.getDenomId())
                    .set(CopyrightWorks::getProdId, productParam.getProdId())
                    .eq(CopyrightWorks::getWorksId, copyrightWorksParam.getWorksId()));

            userCopyrightService.update(new LambdaUpdateWrapper<UserCopyright>()
                    .set(UserCopyright::getStatus, 1)
                    .eq(UserCopyright::getUserId, userCopyright.getUserId()));
        }
        // 审核不通过
        if (copyrightWorksParam.getStatus().equals("3")) {
            // 更新产权登记作品申请状态
            copyrightWorksService.update(new LambdaUpdateWrapper<CopyrightWorks>()
                    .set(CopyrightWorks::getStatus, copyrightWorksParam.getStatus())
                    .set(StrUtil.isNotBlank(copyrightWorksParam.getReason()), CopyrightWorks::getReason, copyrightWorksParam.getReason())
                    .set(StrUtil.isNotBlank(copyrightWorksParam.getReasonStatus()), CopyrightWorks::getReasonStatus, copyrightWorksParam.getReasonStatus())
                    // .set(CopyrightWorks::getShopId, SecurityUtils.getShopUser().getShopId())
                    .eq(CopyrightWorks::getWorksId, copyrightWorksParam.getWorksId()));
        }
        return ServerResponseEntity.success();
    }

    @NotNull
    private static ProductParam buildProductParam(CopyrightWorks copyrightWorks, NftDenom nftDenom, NftApply nftApply, UserCopyright userCopyright) {
        ProductParam productParam = new ProductParam();
        productParam.setProdName(copyrightWorks.getWorksName());
        productParam.setPic(copyrightWorks.getWorksCoverUrl());
        productParam.setImgs(copyrightWorks.getWorksCoverUrl());
        productParam.setOriPrice(0.00);
        productParam.setPrice(0.00);
        productParam.setStatus(8);
        productParam.setEmployeeId(SecurityUtils.getShopUser().getEmployeeId());
        productParam.setShopId(SecurityUtils.getShopUser().getShopId());
        productParam.setProdType(ProdType.PROD_TYPE_NORMAL.value());
        productParam.setMold(2);
        if(copyrightWorks.getWorksName().contains("测试")){
            productParam.setCategoryId(8L);
            productParam.setShopCategoryId(30L);
        }else{
            productParam.setCategoryId(293L);
            productParam.setShopCategoryId(305L);
        }
        productParam.setBrandId(0L);
        productParam.setChain("dt");
        productParam.setMaxNum(1);
        productParam.setTotalStocks(1);
        productParam.setUseLang(0);
        // 默认语言
        List<ProdLangParam> prodLangParams = new ArrayList<>();
        ProdLangParam param = new ProdLangParam();
        param.setLang(0);
        param.setProdName(copyrightWorks.getWorksName());
        prodLangParams.add(param);
        productParam.setProdLangList(prodLangParams);
        List<Sku> skuList = new ArrayList<>();
        Sku sku = new Sku();
        sku.setOriPrice(0.00);
        sku.setPrice(0.00);
        sku.setSkuName("虚拟商品");
        sku.setProperties("虚拟商品:001");
        sku.setStatus(1);
        sku.setStockWarning(0);
        sku.setStocks(1);
        List<SkuLang> skuLangList = new ArrayList<>();
        SkuLang skuLang = new SkuLang();
        skuLang.setLang(0);
        skuLang.setProdName("虚拟商品:001");
        skuLang.setProperties("虚拟商品:001");
        skuLang.setSkuId(0L);
        skuLang.setSkuName("001");
        skuLangList.add(skuLang);
        sku.setSkuLangList(skuLangList);
        skuList.add(sku);
        productParam.setSkuList(skuList);

        ProdNft virtualProductForm = new ProdNft();
        virtualProductForm.setAttr(1);
        virtualProductForm.setAuthorName(userCopyright.getOwnerName());
        virtualProductForm.setBlessingNumber(1);
        virtualProductForm.setCirculation(1);
        virtualProductForm.setDayNum(1);
        virtualProductForm.setDenomId(nftDenom.getDenomId());
        virtualProductForm.setDenomName(nftDenom.getDenomName());
        virtualProductForm.setIssueName(nftApply.getShopName());
        virtualProductForm.setIsGoods(0);
        virtualProductForm.setIsPresenter(0);
        virtualProductForm.setIsRed(1);
        virtualProductForm.setIsScan(0);
        virtualProductForm.setIsTransfer(0);
        virtualProductForm.setLevelId(1);
        virtualProductForm.setModelType("1");
        productParam.setVirtualProductForm(virtualProductForm);
        return productParam;
    }

    @NotNull
    private static NftApply nftApply(NftDenom nftDenom, CopyrightWorks copyrightWorks) {
        NftApply nftApply = new NftApply();
        nftApply.setShopId(SecurityUtils.getShopUser().getShopId());
        nftApply.setDenomId(nftDenom.getDenomId());
        nftApply.setNftName(nftDenom.getDenomName());
        nftApply.setNftNum(1);
        NftApplyImg nftApplyImg = new NftApplyImg();
        nftApplyImg.setImgName(nftDenom.getDenomName());
        nftApplyImg.setImgThumbnail(copyrightWorks.getWorksCoverUrl());
        nftApplyImg.setImgType(copyrightWorks.getWorksType().equals("B") ? 2 : 1);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("sourceFile",copyrightWorks.getWorkFileUrl());
        jsonObject.put("cloudRenderingId","");
        jsonObject.put("modelMtl","");
        jsonObject.put("modelJpg","");
        jsonObject.put("sourceUrlPdf","");
        nftApplyImg.setImgUrl(jsonObject.toJSONString());
        nftApplyImg.setIsReplaceUrl(0);
        nftApplyImg.setIsWatermark(0);
        nftApply.setNftApplyImg(nftApplyImg);
        return nftApply;
    }
}

